package com.xbongbong.paas.script.controller;

import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.model.BusinessRuleInfoModel;
import com.xbongbong.paas.model.PaasProcessTaskModel;
import com.xbongbong.paas.pojo.workflow.UpdateWorkflowStatusPOJO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.redis.RedisTimeConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.workflow.UpgradeService;
import com.xbongbong.workflow.pojo.UpgradeToWorkflowDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
 * 工作流升级给admin用的
 * @author 魏荣杰
 *
 */
@Slf4j
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/wokflow")
public class WorkflowUpgradeForAdminController {

    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private UpgradeService upgradeService;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private BusinessRuleInfoModel businessRuleInfoModel;
    @Resource
    private PaasProcessTaskModel paasProcessTaskModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private UserModel userModel;


    @RequestMapping(value = "/updateWorkflow", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void updateWorkflow(@RequestBody @Valid UpgradeToWorkflowDTO upgradeToWorkflowDTO, BindingResult br) throws XbbException {

        if (!proBaseConfig.getXbbCode().equals(upgradeToWorkflowDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        String corpid = upgradeToWorkflowDTO.getCorpid();


        UpdateWorkflowStatusPOJO updateWorkflowStatusPOJO = new UpdateWorkflowStatusPOJO();
        updateWorkflowStatusPOJO.setIsStart(BasicConstant.ONE);
        paasRedisHelper.setValue(RedisPrefixConstant.UPDATE_WORKFLOW_STATUS, corpid, updateWorkflowStatusPOJO, TimeConstant.SECONDS_PER_DAY);
        try {

            // 取一个超管老板当创建人
            List<UserEntity> usersByRoleId = userModel.getUsersByRoleId(corpid, Arrays.asList(1, 2));
            if (CollectionsUtil.isNotEmpty(usersByRoleId)) {
                upgradeToWorkflowDTO.setUserId(usersByRoleId.get(0).getUserId());
            } else {
                Map<String, Object> userParam = new HashMap<>();
                userParam.put(ParameterConstant.CORPID, corpid);
                userParam.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                List<UserEntity> entitys = userModel.findEntitys(userParam);
                if (CollectionsUtil.isNotEmpty(entitys)) {
                    upgradeToWorkflowDTO.setUserId(entitys.get(0).getUserId());
                } else {
                    updateWorkflowStatusPOJO.setErrorMsg("该公司没有用户");
                    updateWorkflowStatusPOJO.setIsSuccess(BasicConstant.ZERO);
                    paasRedisHelper.setValue(RedisPrefixConstant.UPDATE_WORKFLOW_STATUS, corpid, updateWorkflowStatusPOJO, TimeConstant.SECONDS_PER_DAY);
                }
            }

            // 校验是否工作流可以迁移
            // 校验有无业务规则，有业务规则不迁移
            Map<String, Object> param = new HashMap<>();
            param.put(ParameterConstant.CORPID, corpid);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(ParameterConstant.ENABLE, BasicConstant.ONE);
            Integer businessRuleCount = businessRuleInfoModel.getEntitysCount(param);
            if (businessRuleCount > 0) {
                updateWorkflowStatusPOJO.setCheckMsg("该用户存在业务规则");
                paasRedisHelper.setValue(RedisPrefixConstant.UPDATE_WORKFLOW_STATUS, corpid, updateWorkflowStatusPOJO, TimeConstant.SECONDS_PER_DAY);
                return;
            }

            // 检验有无未处理完的审批，有数据不迁移
            param.clear();
            param.put(ParameterConstant.CORPID, corpid);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put("flowStatusIn", Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(),FlowStatusEnum.IN_APPROVAL.getType()));
            Integer processTaskCount = paasProcessTaskModel.getEntitysCount(param);
            if (processTaskCount > 0) {
                updateWorkflowStatusPOJO.setCheckMsg("该用户仍有未处理完的审批");
                updateWorkflowStatusPOJO.setIsSuccess(BasicConstant.ZERO);
                paasRedisHelper.setValue(RedisPrefixConstant.UPDATE_WORKFLOW_STATUS, corpid, updateWorkflowStatusPOJO, TimeConstant.SECONDS_PER_DAY);
                return;
            }

            // 开始迁移工作流
            String result = upgradeService.upgradeBusinessRule(upgradeToWorkflowDTO);
            if (Objects.equals(result, "success")) {
                // 迁移完成，切换到工作流
                CompanyConfigEntity configModelByConfigAlias = companyConfigModel.getByConfigAlias(CompanyConfigEnum.WORKFLOW.getAlias(), corpid);
                if (Objects.isNull(configModelByConfigAlias)) {
                    configModelByConfigAlias = new CompanyConfigEntity();
                    configModelByConfigAlias.setConfigAlias(CompanyConfigEnum.WORKFLOW.getAlias());
                    configModelByConfigAlias.setConfigName(CompanyConfigEnum.WORKFLOW.getName());
                    configModelByConfigAlias.setConfigValue(BasicConstant.ONE_STRING);
                    configModelByConfigAlias.setCorpid(corpid);
                    companyConfigModel.insert(configModelByConfigAlias);
                } else {
                    configModelByConfigAlias.setConfigValue(BasicConstant.ONE_STRING);
                    companyConfigModel.update(configModelByConfigAlias);
                }
                paasRedisHelper.setValue(CompanyConfigEnum.WORKFLOW.getAlias(), corpid, BasicConstant.ONE_STRING, RedisTimeConstant.TEN_MINUTES);

                // 成功迁移
                updateWorkflowStatusPOJO.setIsSuccess(BasicConstant.ONE);
                paasRedisHelper.setValue(RedisPrefixConstant.UPDATE_WORKFLOW_STATUS, corpid, updateWorkflowStatusPOJO, TimeConstant.SECONDS_PER_DAY);
            } else {
                // 迁移失败，报错返回
                updateWorkflowStatusPOJO.setErrorMsg(result);
                updateWorkflowStatusPOJO.setIsSuccess(BasicConstant.ZERO);
                paasRedisHelper.setValue(RedisPrefixConstant.UPDATE_WORKFLOW_STATUS, corpid, updateWorkflowStatusPOJO, TimeConstant.SECONDS_PER_DAY);
            }



        } catch (Exception e) {
            updateWorkflowStatusPOJO.setErrorMsg(e.getMessage());
            updateWorkflowStatusPOJO.setIsSuccess(BasicConstant.ZERO);
            paasRedisHelper.setValue(RedisPrefixConstant.UPDATE_WORKFLOW_STATUS, corpid, updateWorkflowStatusPOJO, TimeConstant.SECONDS_PER_DAY);
            log.error("com.xbongbong.paas.script.controller.WorkflowUpgradeForAdminController.updateWorkflow fail", e);
        }

    }
}
